package com.elem.dao.impl;

import com.elem.bean.DeliveryAddress;
import com.elem.dao.DeliveryAddressDao;
import com.elem.util.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class DeliveryAddressDaoImpl implements DeliveryAddressDao {
//   创建JdbcTemplate对象
    JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());
    @Override
    public DeliveryAddress getDeliveryAddressById(String daId) throws Exception {
//        得到地址的  daId
        String sql="select * from deliveryaddress where daId=?";
        DeliveryAddress deliveryAddress = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(DeliveryAddress.class), daId);
        return deliveryAddress;
    }

    @Override
    public int saveDeliveryAddress(DeliveryAddress deliveryAddress) throws Exception {
//      获取DeliveryAddress保存的收货地址
        String sql="insert into deliveryaddress(contactName,contactSex,contactTel,address,userId) values(?,?,?,?,?)";
        int row = jdbcTemplate.update(sql, deliveryAddress.getContactName(), deliveryAddress.getContactSex(), deliveryAddress.getContactTel(), deliveryAddress.getAddress(), deliveryAddress.getUserId());
        return row;//1 表示保存成功 0表示保存失败
    }

    @Override
    public List<DeliveryAddress> listDeliveryAddressByUserId(String userId) throws Exception {
        //        获取DeliveryAddress所有的收货地址
        String sql="select * from deliveryaddress where userId=?";
        List<DeliveryAddress> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(DeliveryAddress.class),userId);
        return list;
    }

    @Override
    public int removeDeliveryAddress(DeliveryAddress deliveryAddress) throws Exception {
        String sql="delete from deliveryaddress where daId=?";
        int row = jdbcTemplate.update(sql, deliveryAddress.getDaId());
        return row;
    }

    @Override
    public int updateDeliveryAddress(DeliveryAddress deliveryAddress) throws Exception {
            String sql="update deliveryaddress set contactName=?,contactTel=?,address=? where daId=?";
            int row = jdbcTemplate.update(sql, deliveryAddress.getContactName(), deliveryAddress.getContactTel(), deliveryAddress.getAddress(), deliveryAddress.getDaId());
            return row;
    }
}
